package com.food.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.food.dao.service.RecipeService;
import com.food.model.Recipe;

/**
 * Servlet implementation class ShowRecipeServlet
 */
@WebServlet("/ViewRecipeServlet")
public class ViewRecipeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewRecipeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		String pageNumberStr = "0";
		if (request.getParameter("pageNumber")!=null) {
			pageNumberStr = request.getParameter("pageNumber");
		}

		int pageNumber = 0;
		
		request.removeAttribute("now");
		request.removeAttribute("pre");
		request.removeAttribute("next");
		request.removeAttribute("last");
		
		
		RecipeService pageService = new RecipeService();
		
		/* 建立 List<Product> */
		List<Recipe> Beanlist = new ArrayList<Recipe>();

		/* 從服務取得 物件集合 */
		// Beanlist = prodsv.findAllProduct();

		// 分頁6筆

		pageNumber = Integer.parseInt(pageNumberStr);
		request.setAttribute("now", pageNumber);
		request.setAttribute("first", "/ViewRecipeServlet?pageNumber=0");
		request.setAttribute("pre", "/ViewRecipeServlet?pageNumber=" + (pageNumber - 1));
		request.setAttribute("next","/ViewRecipeServlet?pageNumber="+( pageNumber + 1));
		
		
		//每頁6筆，頁數
		Beanlist = pageService.findAllRecipePages(9, pageNumber);
		
		

		
		List<Recipe> recoll = pageService.findAllRecipe();	
		
		int last = recoll.size()/9;
		request.setAttribute("toEnd", "/ViewRecipeServlet?pageNumber="+last);
		request.setAttribute("total", last);
		
		if(last==pageNumber){
		request.setAttribute("last", last);
		}
		
		String pages="";
		for(int i=0 ;i<=last;i++){
			pages=pages+"<td><a href=\"ViewRecipeServlet?pageNumber="+i+"\">"+(i+1)+"</a></td>";
			
		}
		
		request.setAttribute("pages", pages);
		request.setAttribute("recipe_show", Beanlist);
		RequestDispatcher rd = request
				.getRequestDispatcher("/recipe/allRecipe.jsp");
		rd.forward(request, response);
		return;
	}

}
